#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量用户组管理对话框模块 - 用于批量创建和管理用户组
"""

import logging
import json
import os
from typing import Dict, List, Any, Optional
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
    QLineEdit, QPushButton, QFormLayout, QDialogButtonBox,
    QComboBox, QSpinBox, QTabWidget, QWidget, QTextEdit,
    QCheckBox, QMessageBox, QTableWidget, QTableWidgetItem,
    QHeaderView, QGroupBox, QRadioButton, QProgressBar,
    QFileDialog
)
from PyQt5.QtCore import Qt, pyqtSlot, QThread, pyqtSignal
from PyQt5.QtGui import QFont

from src.zabbix_api import ZabbixAPI

logger = logging.getLogger(__name__)

class UserGroupDialog(QDialog):
    """批量用户组管理对话框"""
    
    def __init__(self, api: ZabbixAPI, parent=None):
        """
        初始化批量用户组管理对话框
        
        Args:
            api (ZabbixAPI): Zabbix API客户端
            parent: 父窗口
        """
        super().__init__(parent)
        self.api = api
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        self.setWindowTitle("批量用户组管理")
        self.resize(800, 600)
        self.setModal(True)
        
        # 创建主布局
        main_layout = QVBoxLayout(self)
        
        # 创建选项卡
        tab_widget = QTabWidget()
        
        # 创建用户组选项卡
        create_tab = QWidget()
        create_layout = QVBoxLayout(create_tab)
        
        # 用户组创建区域
        create_group = QGroupBox("批量创建用户组")
        create_form = QFormLayout(create_group)
        
        # 用户组前缀
        self.prefix_edit = QLineEdit()
        self.prefix_edit.setPlaceholderText("例如: DEV_")
        create_form.addRow("用户组前缀:", self.prefix_edit)
        
        # 用户组列表
        self.groups_text = QTextEdit()
        self.groups_text.setPlaceholderText("每行一个用户组名称，例如:\n项目A\n项目B\n项目C")
        create_form.addRow("用户组列表:", self.groups_text)
        
        # 权限设置
        permission_group = QGroupBox("权限设置")
        permission_layout = QVBoxLayout(permission_group)
        
        # 前端访问权限
        self.gui_access = QComboBox()
        self.gui_access.addItem("默认 (使用系统默认方法)", "0")
        self.gui_access.addItem("内部系统认证", "1")
        self.gui_access.addItem("禁用", "2")
        
        # 用户状态
        self.user_status = QComboBox()
        self.user_status.addItem("启用", "0")
        self.user_status.addItem("禁用", "1")
        
        # 调试模式
        self.debug_mode = QComboBox()
        self.debug_mode.addItem("禁用", "0")
        self.debug_mode.addItem("启用", "1")
        
        # 添加到布局
        permission_form = QFormLayout()
        permission_form.addRow("前端访问:", self.gui_access)
        permission_form.addRow("用户状态:", self.user_status)
        permission_form.addRow("调试模式:", self.debug_mode)
        permission_layout.addLayout(permission_form)
        
        # 主机组权限
        hostgroup_perm = QGroupBox("主机组权限")
        hostgroup_layout = QVBoxLayout(hostgroup_perm)
        
        # 添加主机组按钮
        self.add_hostgroup_btn = QPushButton("添加主机组权限")
        self.add_hostgroup_btn.clicked.connect(self.on_add_hostgroup)
        hostgroup_layout.addWidget(self.add_hostgroup_btn)
        
        # 主机组权限表格
        self.hostgroup_table = QTableWidget(0, 3)
        self.hostgroup_table.setHorizontalHeaderLabels(["主机组", "权限", "操作"])
        self.hostgroup_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.hostgroup_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.hostgroup_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        hostgroup_layout.addWidget(self.hostgroup_table)
        
        permission_layout.addWidget(hostgroup_perm)
        
        # 添加到创建选项卡
        create_layout.addWidget(create_group)
        create_layout.addWidget(permission_group)
        
        # 创建按钮
        create_button = QPushButton("批量创建用户组")
        create_button.clicked.connect(self.on_create_groups)
        create_layout.addWidget(create_button)
        
        # 创建状态文本
        self.status_text = QTextEdit()
        self.status_text.setReadOnly(True)
        self.status_text.setMaximumHeight(150)
        create_layout.addWidget(self.status_text)
        
        # 添加到选项卡
        tab_widget.addTab(create_tab, "批量创建")
        
        # 管理选项卡
        manage_tab = QWidget()
        manage_layout = QVBoxLayout(manage_tab)
        
        # 刷新和搜索区域
        search_layout = QHBoxLayout()
        
        # 搜索框
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("搜索用户组")
        self.search_edit.textChanged.connect(self.on_search)
        search_layout.addWidget(self.search_edit)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self.load_usergroups)
        search_layout.addWidget(refresh_btn)
        
        manage_layout.addLayout(search_layout)
        
        # 用户组表格
        self.usergroup_table = QTableWidget(0, 4)
        self.usergroup_table.setHorizontalHeaderLabels(["ID", "名称", "成员数", "操作"])
        self.usergroup_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.usergroup_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.usergroup_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.usergroup_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        manage_layout.addWidget(self.usergroup_table)
        
        # 添加到选项卡
        tab_widget.addTab(manage_tab, "管理用户组")
        
        # 添加选项卡到主布局
        main_layout.addWidget(tab_widget)
        
        # 添加按钮盒子
        button_box = QDialogButtonBox(QDialogButtonBox.Close)
        button_box.rejected.connect(self.reject)
        main_layout.addWidget(button_box)
        
        # 加载用户组
        self.load_usergroups()
    
    def load_usergroups(self):
        """加载用户组列表"""
        try:
            # 清空表格
            self.usergroup_table.setRowCount(0)
            
            # 获取用户组
            usergroups = self.api.get_usergroups()
            
            # 添加到表格
            for i, group in enumerate(usergroups):
                self.usergroup_table.insertRow(i)
                
                # ID
                id_item = QTableWidgetItem(group.get('usrgrpid', ''))
                id_item.setFlags(id_item.flags() & ~Qt.ItemIsEditable)
                self.usergroup_table.setItem(i, 0, id_item)
                
                # 名称
                name_item = QTableWidgetItem(group.get('name', ''))
                name_item.setFlags(name_item.flags() & ~Qt.ItemIsEditable)
                self.usergroup_table.setItem(i, 1, name_item)
                
                # 成员数
                try:
                    users = self.api.get_users_in_group(group.get('usrgrpid', ''))
                    count_item = QTableWidgetItem(str(len(users)))
                except:
                    count_item = QTableWidgetItem("0")
                count_item.setFlags(count_item.flags() & ~Qt.ItemIsEditable)
                self.usergroup_table.setItem(i, 2, count_item)
                
                # 操作按钮
                cell_widget = QWidget()
                layout = QHBoxLayout(cell_widget)
                layout.setContentsMargins(2, 2, 2, 2)
                
                view_btn = QPushButton("查看")
                view_btn.setProperty("usrgrpid", group.get('usrgrpid', ''))
                view_btn.clicked.connect(self.on_view_group)
                layout.addWidget(view_btn)
                
                delete_btn = QPushButton("删除")
                delete_btn.setProperty("usrgrpid", group.get('usrgrpid', ''))
                delete_btn.setProperty("name", group.get('name', ''))
                delete_btn.clicked.connect(self.on_delete_group)
                layout.addWidget(delete_btn)
                
                self.usergroup_table.setCellWidget(i, 3, cell_widget)
            
            self.usergroup_table.sortItems(1)  # 按名称排序
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"加载用户组失败: {str(e)}")
            logger.error(f"加载用户组失败: {str(e)}")
    
    def on_search(self, text):
        """搜索用户组"""
        for i in range(self.usergroup_table.rowCount()):
            name = self.usergroup_table.item(i, 1).text()
            self.usergroup_table.setRowHidden(i, text.lower() not in name.lower())
    
    def on_view_group(self):
        """查看用户组详情"""
        button = self.sender()
        usrgrpid = button.property("usrgrpid")
        
        try:
            # 获取用户组详情
            group = self.api.get_usergroup_by_id(usrgrpid)
            
            # 获取用户组成员
            users = self.api.get_users_in_group(usrgrpid)
            
            # 显示详情
            info = f"用户组ID: {group.get('usrgrpid', '')}\n"
            info += f"名称: {group.get('name', '')}\n"
            info += f"前端访问: {self.get_gui_access_text(group.get('gui_access', '0'))}\n"
            info += f"用户状态: {self.get_user_status_text(group.get('users_status', '0'))}\n"
            info += f"调试模式: {self.get_debug_mode_text(group.get('debug_mode', '0'))}\n\n"
            
            info += f"成员列表 ({len(users)}):\n"
            for user in users:
                info += f"- {user.get('username', '')} ({user.get('name', '')} {user.get('surname', '')})\n"
            
            # 权限信息
            info += "\n主机组权限:\n"
            for perm in group.get('rights', []):
                hostgroup = self.api.get_hostgroup_by_id(perm.get('id', ''))
                info += f"- {hostgroup.get('name', '')} : {self.get_permission_text(perm.get('permission', '0'))}\n"
            
            # 显示对话框
            QMessageBox.information(self, f"用户组: {group.get('name', '')}", info)
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"获取用户组详情失败: {str(e)}")
            logger.error(f"获取用户组详情失败: {str(e)}")
    
    def on_delete_group(self):
        """删除用户组"""
        button = self.sender()
        usrgrpid = button.property("usrgrpid")
        name = button.property("name")
        
        # 确认删除
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除用户组 '{name}' 吗？\n该操作不可撤销！",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
        
        try:
            # 删除用户组
            result = self.api.delete_usergroup(usrgrpid)
            
            if result:
                QMessageBox.information(self, "成功", f"用户组 '{name}' 已成功删除。")
                # 刷新列表
                self.load_usergroups()
            else:
                QMessageBox.warning(self, "失败", f"删除用户组 '{name}' 失败。")
        
        except Exception as e:
            QMessageBox.warning(self, "错误", f"删除用户组失败: {str(e)}")
            logger.error(f"删除用户组失败: {str(e)}")
    
    def on_add_hostgroup(self):
        """添加主机组权限"""
        try:
            # 获取主机组列表
            hostgroups = self.api.get_hostgroups()
            
            # 添加一行
            row = self.hostgroup_table.rowCount()
            self.hostgroup_table.insertRow(row)
            
            # 主机组下拉框
            combo = QComboBox()
            for group in hostgroups:
                combo.addItem(group.get('name', ''), group.get('groupid', ''))
            self.hostgroup_table.setCellWidget(row, 0, combo)
            
            # 权限下拉框
            perm_combo = QComboBox()
            perm_combo.addItem("拒绝", "0")
            perm_combo.addItem("只读", "2")
            perm_combo.addItem("读写", "3")
            perm_combo.setCurrentIndex(2)  # 默认选择读写
            self.hostgroup_table.setCellWidget(row, 1, perm_combo)
            
            # 删除按钮
            cell_widget = QWidget()
            layout = QHBoxLayout(cell_widget)
            layout.setContentsMargins(2, 2, 2, 2)
            
            delete_btn = QPushButton("删除")
            delete_btn.clicked.connect(lambda: self.on_delete_hostgroup_row(row))
            layout.addWidget(delete_btn)
            
            self.hostgroup_table.setCellWidget(row, 2, cell_widget)
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"加载主机组失败: {str(e)}")
            logger.error(f"加载主机组失败: {str(e)}")
    
    def on_delete_hostgroup_row(self, row):
        """删除主机组权限行"""
        self.hostgroup_table.removeRow(row)
    
    def on_create_groups(self):
        """批量创建用户组"""
        # 获取用户组信息
        prefix = self.prefix_edit.text()
        groups_text = self.groups_text.toPlainText()
        
        if not groups_text.strip():
            QMessageBox.warning(self, "错误", "请输入要创建的用户组列表")
            return
        
        # 解析用户组列表
        groups = [line.strip() for line in groups_text.splitlines() if line.strip()]
        
        if not groups:
            QMessageBox.warning(self, "错误", "请输入有效的用户组列表")
            return
        
        # 获取权限设置
        gui_access = self.gui_access.currentData()
        user_status = self.user_status.currentData()
        debug_mode = self.debug_mode.currentData()
        
        # 获取主机组权限
        hostgroup_rights = []
        for row in range(self.hostgroup_table.rowCount()):
            hostgroup_combo = self.hostgroup_table.cellWidget(row, 0)
            perm_combo = self.hostgroup_table.cellWidget(row, 1)
            
            hostgroup_id = hostgroup_combo.currentData()
            permission = perm_combo.currentData()
            
            hostgroup_rights.append({
                "id": hostgroup_id,
                "permission": permission
            })
        
        # 确认创建
        confirm_msg = f"将创建以下 {len(groups)} 个用户组:\n"
        for group in groups:
            group_name = f"{prefix}{group}" if prefix else group
            confirm_msg += f"- {group_name}\n"
        
        reply = QMessageBox.question(
            self,
            "确认创建",
            confirm_msg,
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
        
        # 创建用户组
        self.status_text.clear()
        success_count = 0
        
        for group in groups:
            group_name = f"{prefix}{group}" if prefix else group
            
            try:
                # 检查用户组是否已存在
                exists = self.api.check_usergroup_exists(group_name)
                
                if exists:
                    self.status_text.append(f"用户组 '{group_name}' 已存在，跳过")
                    continue
                
                # 创建用户组
                params = {
                    "name": group_name,
                    "gui_access": gui_access,
                    "users_status": user_status,
                    "debug_mode": debug_mode
                }
                
                if hostgroup_rights:
                    params["rights"] = hostgroup_rights
                
                result = self.api.create_usergroup(params)
                
                if result:
                    success_count += 1
                    self.status_text.append(f"用户组 '{group_name}' 创建成功")
                else:
                    self.status_text.append(f"用户组 '{group_name}' 创建失败")
                
            except Exception as e:
                self.status_text.append(f"创建用户组 '{group_name}' 出错: {str(e)}")
                logger.error(f"创建用户组 '{group_name}' 出错: {str(e)}")
        
        # 显示结果
        self.status_text.append(f"\n批量创建完成，成功创建 {success_count} 个用户组")
        
        # 刷新用户组列表
        self.load_usergroups()
    
    def get_gui_access_text(self, value):
        """获取前端访问权限文本"""
        mapping = {
            "0": "默认",
            "1": "内部系统认证",
            "2": "禁用"
        }
        return mapping.get(value, "未知")
    
    def get_user_status_text(self, value):
        """获取用户状态文本"""
        mapping = {
            "0": "启用",
            "1": "禁用"
        }
        return mapping.get(value, "未知")
    
    def get_debug_mode_text(self, value):
        """获取调试模式文本"""
        mapping = {
            "0": "禁用",
            "1": "启用"
        }
        return mapping.get(value, "未知")
    
    def get_permission_text(self, value):
        """获取权限文本"""
        mapping = {
            "0": "拒绝",
            "2": "只读",
            "3": "读写"
        }
        return mapping.get(value, "未知") 